package cn.felord.mongodb.controller;

import cn.felord.mongodb.dao.BookDao;
import cn.felord.mongodb.dao.FileEntityDao;
import cn.felord.mongodb.entity.Book;
import cn.felord.mongodb.entity.FileEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author dax.
 * @version v1.0
 * @since 2018/3/1 14:14
 */
@RestController
@RequestMapping("/mongo")
public class MongoController {
    @Resource
    private BookDao bookDao;
    @Resource
    private FileEntityDao fileEntityDao;
    @RequestMapping("/add")
    public void test() {
        Book book = new Book();

        book.setId("aaadfaf");
        book.setAuthor("罗贯中");
        book.setName("三国演义");
        book.setType("古典文学");

        bookDao.save(book);

    }
    @RequestMapping("/update")
    public void update(MultipartFile multipartFile) throws IOException {

        String originalFilename = multipartFile.getOriginalFilename();
        byte[] datas = multipartFile.getBytes();
        String contentType = multipartFile.getContentType();
        String name = multipartFile.getName();

        FileEntity fileEntity=new FileEntity();

          fileEntity.setOriginalFilename(originalFilename);
          fileEntity.setDatas(datas);
          fileEntity.setConentType(contentType);
          fileEntity.setName(name);

        fileEntityDao.save(fileEntity);
    }
    @RequestMapping("/read")
    public void read(HttpServletResponse response,  String name) throws IOException {
        FileEntity fileEntity=fileEntityDao.findByName(name);

      ServletOutputStream outputStream= response.getOutputStream();
                outputStream.write(fileEntity.getDatas());

    }

}
